package thread.waitandnotify;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 写线程： 一个线程向集合中添加数据，添加完数据通知另外的线程去集合中读取数据
 * 读线程：从集合中读取数据，集合中没有数据就等待
 *
 * @author liweimin
 * @date 2021/4/30 16:46
 * @since
 */
public class Test7 {
    static List list = new ArrayList<>();
    static final Object obj = new Object();

    /**
     * read from list
     */
    public static void read() {

        synchronized (obj) {
//            if (null == list || list.size() == 0) {//if判断 可能导致 读线程都堵在这里 等待唤醒 一个读线程先唤醒 取完数据 第二个读线程 数组越界
            while (null == list || list.size() == 0) {//使用while去解决
                System.out.println(Thread.currentThread().getName() + " begin wait...");
                try {
                    obj.wait();//wait
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " end wait...");
            }
            Object data = list.remove(0);
            System.out.println(Thread.currentThread().getName() + "从集合中取了" + data + "后，集合中数据的数量：" + list.size());
        }


    }

    /**
     * write date to list
     */
    public static void write() {
        synchronized (obj) {
            String data = "date" + System.currentTimeMillis();
            list.add(data);
            System.out.println(Thread.currentThread().getName() + "向集合写入了数据：" + data);
            obj.notifyAll();
//            obj.notify();
        }
    }

    public static void main(String[] args) throws InterruptedException {

        new Thread(Test7::read, "read_thread_1").start();
        new Thread(Test7::read, "read_thread_2").start();


        TimeUnit.SECONDS.sleep(1);

        new Thread(Test7::write, "write_thread").start();
//        new Thread(Test7::write, "write_thread").start();
//        new Thread(Test7::read, "read_thread").start();
    }
}
